<template>
  <view>
    <view class="login-top">
      <image src="https://s2.loli.net/2022/05/05/9cO2szbaipAJlHN.png" mode=""></image>
    </view>
    <view v-if="isTestLogin" class="example">
      <view class="testLogin">
        <uni-easyinput :styles="styles" :trim="true" prefixIcon="person" type="text" v-model="username" placeholder="测试账号: admin"></uni-easyinput>
      </view>
      <view class="testLogin">
        <uni-easyinput :styles="styles" :trim="true" prefixIcon="locked" type="password" v-model="password" placeholder="测试密码: 000000"></uni-easyinput>
      </view>
      <view class="login-button2">
        <button type="default" @click="isTestLogin=false">返回</button>
        <button type="default" @click="loginTestUser">登录</button>
      </view>
    </view>
    <view v-else>
      <view class="login-button">
        <button type="default" @click="userLogin">微信快捷登录</button>
      </view>
      <view class="login-button1">
        <button type="default" @click="userTestLogin">测试号登录</button>
      </view>
    </view>
  </view>
</template>

<script>
  import {mapState,mapMutations} from 'vuex'
  export default {
  	data() {
  		return {
        // 测试账号
        username: '',
        // 测试密码
         password: '',
         isTestLogin: false,
         // 输入框样式
         styles: {
         					borderColor: '#A3844F'
          }
  		};
  	},
    computed: {
      ...mapState('user_module',['userinfo'])
    },
    methods: {
      ...mapMutations('user_module',['updateisLogin','updateUserInfo','updateToken','updateUserPhone','updateUserEmail','updateUserName','updateUserSex','updateUserId']),
      ...mapMutations('postitem_module',['updatePostItem','updateIsDot']),
      // 测试账号登录
      async loginTestUser() {
        const {data:res} = await uni.$http.post(`/login/by/test/account?username=${this.username}&password=${this.password}`)
        console.log(res)
        if(!res) return uni.$showMsg('用户或密码错误！')
        this.updateToken(res)
        this.updateisLogin(true)
        const {data:{data:{uid}}} = await uni.$http.get('/api/user/index/get/uid').catch(err => err)
        uni.setStorageSync('userId',uid)
        let query = {
          avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/Mo3Nj0WZJLHjR8qBKicrOuiaLyby4icxW7Ps1vibEcBoXZujJtOZ1KpYQ2hM7NlFaR0UmMd9tVBdibrGZwCqck12lcA/132",
          nickName: "小羊努力干饭"
        }
        this.updateUserInfo(query)
        this.getUserInfo()
        uni.$showMsg('您已成功登录！')
      },
      async userTestLogin() {
        this.isTestLogin = true
      },
      // 获取用户信息
      async getUserInfo() {
        const {data:{data:{currentUser:res}},data:info} = await uni.$http.post('/api/user/index/getUserInfo').catch(err => uni.$showMsg('网络错误！'))
        if(info.code !== 200) return uni.$showMsg('获取用户信息失败，请重新尝试！')
        this.updateUserName(res.nickname)
        this.updateUserPhone(res.mobile)
        this.updateUserEmail(res.email)
        this.updateUserSex(res.sex)
        this.updateUserId(res.id)
      },
      // 微信登录
      userLogin() {
        uni.getUserProfile({
              desc: '用于个人信息展示', // 声明获取用户个人信息后的用途，后续会展示在弹窗中
              success: (res) => {
                uni.setStorageSync('tokenTest',true)
                this.updateUserInfo(res.userInfo)
                this.getToken(res)
                uni.showLoading({
                  title: '正在登录....'
                })
                //test
                setTimeout(() => {
                  uni.hideLoading()
                },1000)
                // 发送post请求发送给服务器nickName和avatarUrl
              },
              fail: (res) => {
                  uni.showModal({
                    text: '提示',
                    content: '您取消了登录授权，将无法正常显示个人信息，点击确定重新获取授权！',
                    success: (res) => {
                      if (res.confirm) {
                            this.userLogin()
                      		} else if (res.cancel) {
                            uni.$showMsg('您取消了登录授权！')
                      		}
                    }
                  })
                }
           })
      },
      async getToken(info) {
        const [err,res] = await uni.login().catch(err => err)
        if(err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
        const query = {
          code: res.code
        }
        const {data: loginResults} = await uni.$http.get('/user/index/login',query)
        if(loginResults.code !== 200) {
          return uni.$showMsg('登录失败')
        }
        this.updateToken(loginResults.data.token)
        this.updateisLogin(true)
        const infoQuery = {
          nickName: info.userInfo.nickName,
          avatarUrl: info.userInfo.avatarUrl
        }
        const {data:results} = await uni.$http.post('/api/user/index/userInfo',infoQuery).catch(err => uni.$showMsg('网络错误！'))
        if(results.code !== 200) return uni.$showMsg('登录失败！')
        const {data:{data:{uid}}} = await uni.$http.get('/api/user/index/get/uid').catch(err => err)
        uni.setStorageSync('userId',uid)
        this.getUserInfo()
        uni.$showMsg('您已成功登录！')
      }
    }
  };
</script>

<style lang="scss">
    .login-top {
      image {
        display: block;
        margin: 20px 20px;
        width: 100%;
        height: 260px;
      }
    }
    .login-button {
      display: flex;
      justify-content: center;
      margin: 60px 0 0 0;
      button {
        border: 1px solid #FFFFFF;
        box-shadow: 0 1px 5px #A3844F;
        border-radius: 20px;
        width: 240px;
      }
    }
    .login-button1 {
      display: flex;
      justify-content: center;
      margin: 20px 0;
      button {
        border: 1px solid #FFFFFF;
        box-shadow: 0 1px 5px #A3844F;
        border-radius: 20px;
        width: 240px;
      }
    }
    //账号密码登录
    .testLogin {
      margin: 15px;
    }
    .login-button2 {
      display: flex;
      justify-content: center;
      margin: 50px 25px;
      button {
        font-size: 14px;
        border: 1px solid #FFFFFF;
        box-shadow: 0 1px 5px #A3844F;
        border-radius: 20px;
        width: 125px;
      }
    }
    .example {
    		padding: 30px 25px;
    		// background-color: #fff;
    	}
    
    	.button {
    		display: flex;
    		align-items: center;
    		height: 35px;
    		margin-left: 10px;
        // background-color: #FCFCF3;
        // border: 1px solid #E56D00;
    	}
      
      .submins {
        width: 250px;
      }
      
      .example-body {
      		background-color: #fff;
      		padding: 10px;
      	}
</style>
